import React, { useState, useEffect } from 'react';
import axios from 'axios';

const SocialInsuranceProofForm = ({ applicationId }) => {
    const [socialInsuranceProofs, setSocialInsuranceProofs] = useState([]);
    const [newProof, setNewProof] = useState({
        insuranceUnit: '',
        verificationStatus: ''
    });
    const [editingId, setEditingId] = useState(null);

    useEffect(() => {
        const fetchSocialInsuranceProofs = async () => {
            try {
                const response = await axios.get(`/api/applications/${applicationId}/social-insurance-proofs`);
                setSocialInsuranceProofs(response.data);
            } catch (error) {
                console.error('Error fetching social insurance proofs:', error);
            }
        };

        if (applicationId) {
            fetchSocialInsuranceProofs();
        }
    }, [applicationId]);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setNewProof(prevInfo => ({
            ...prevInfo,
            [name]: value
        }));
    };

    const handleAddOrUpdate = async (e) => {
        e.preventDefault();
        try {
            if (editingId) {
                await axios.put(`/api/applications/${applicationId}/social-insurance-proofs/${editingId}`, newProof);
                alert('社保缴费证明更新成功！');
            } else {
                await axios.post(`/api/applications/${applicationId}/social-insurance-proofs`, newProof);
                alert('社保缴费证明添加成功！');
            }
            setNewProof({
                insuranceUnit: '',
                verificationStatus: ''
            });
            setEditingId(null);
            const response = await axios.get(`/api/applications/${applicationId}/social-insurance-proofs`);
            setSocialInsuranceProofs(response.data);
        } catch (error) {
            console.error('Error saving social insurance proof:', error);
            alert('保存失败，请重试。');
        }
    };

    const handleEdit = (info) => {
        setNewProof(info);
        setEditingId(info.id);
    };

    const handleDelete = async (id) => {
        try {
            await axios.delete(`/api/applications/${applicationId}/social-insurance-proofs/${id}`);
            alert('社保缴费证明删除成功！');
            setSocialInsuranceProofs(socialInsuranceProofs.filter(info => info.id !== id));
        } catch (error) {
            console.error('Error deleting social insurance proof:', error);
            alert('删除失败，请重试。');
        }
    };

    return (
        <div className="form-container">
            <h3>社保缴费证明</h3>
            <form onSubmit={handleAddOrUpdate}>
                <div className="form-group">
                    <label>参保单位:</label>
                    <input type="text" name="insuranceUnit" value={newProof.insuranceUnit} onChange={handleChange} required />
                </div>
                <div className="form-group">
                    <label>核验状态:</label>
                    <input type="text" name="verificationStatus" value={newProof.verificationStatus} onChange={handleChange} />
                </div>
                <button type="submit">{editingId ? '更新' : '添加'}</button>
            </form>

            <h4>已添加社保缴费证明</h4>
            <table>
                <thead>
                    <tr>
                        <th>参保单位</th>
                        <th>核验状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {socialInsuranceProofs.map(info => (
                        <tr key={info.id}>
                            <td>{info.insuranceUnit}</td>
                            <td>{info.verificationStatus}</td>
                            <td>
                                <button onClick={() => handleEdit(info)}>编辑</button>
                                <button onClick={() => handleDelete(info.id)}>删除</button>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default SocialInsuranceProofForm;

